/**
 * 
 */
package com.pos;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.pos.modules.LoginActivity;
import com.pos.net.netparam.NetParams;
import com.pos.net.request.DownloadRequest;
import com.pos.net.request.JsonNetRequest;
import com.pos.net.request.interfa.LoadListener;
import com.pos.set.AppSet;
import com.pos.toolbox.file.InstallUtils;
import com.pos.widgets.dialog.UpdateDialog;

import de.greenrobot.event.Subscribe;

/**
 * @description:基础activity类(抽象)
 * @author cai
 * @time:2015年11月12日上午11:15:24
 */
public abstract class BaseActivity extends FragmentActivity {
	public Context mContext;
	public JsonNetRequest netRequest;
	public ProgressDialog dialog;
	public UpdateDialog updateDialog;
	public String downLoadUrl, downLoadMsg;

	@SuppressWarnings("unchecked")
	protected <T extends View> T bindId(int id) {
		return (T) findViewById(id);
	}

	@SuppressWarnings("unchecked")
	protected <T extends View> T bindId(View view, int id) {
		return (T) view.findViewById(id);
	}

	/**
	 * log打印需要用到的标签
	 */
	public static String Tag = "BaseActivity";

	@Subscribe
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
		mContext = this;
		Tag = this.getClass().getSimpleName();
		netRequest = JsonNetRequest.getInstance(mContext);
		netRequest.setMainContext(mContext);
		updateDialog = new UpdateDialog(mContext);
		updateDialog.setCancelable(false);
		AppSet.activityStack.add(this);
		initView();
		initData();
		initListener();
	}

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	/**
	 * 初始化视图
	 */
	public abstract void initView();

	/**
	 * 初始化数据
	 */
	public abstract void initData();

	/**
	 * 初始化监听事件
	 */
	public abstract void initListener();

	/**
	 * toast短提示
	 * 
	 * @param text
	 *            提示语
	 */
	public void showShortToast(String text) {
		Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
	}

	/**
	 * toast短提示
	 * 
	 * @param stringId
	 *            string资源
	 */
	public void showShortToast(int stringId) {
		Toast.makeText(mContext, stringId, Toast.LENGTH_SHORT).show();
	}

	/**
	 * toast短提示
	 * 
	 * @param text
	 *            提示语
	 */
	public void showLongToast(String text) {
		Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
	}

	/**
	 * toast长提示
	 * 
	 * @param stringId
	 *            string资源
	 */
	public void showLongToast(int stringId) {
		Toast.makeText(mContext, stringId, Toast.LENGTH_LONG).show();
	}

	/**
	 * startActivity
	 * 
	 * @param activityClass
	 *            即将启动的activity类
	 */
	public void startActivity(Class<? extends Activity> activityClass) {
		Intent intent = new Intent(mContext, activityClass);
		startActivity(intent);
	}

	public void showDialg() {
		try {
			if (dialog == null) {
				dialog = new ProgressDialog(mContext);
				dialog.setCanceledOnTouchOutside(false);
			}
			if (!dialog.isShowing()) {
				dialog.setMessage(getString(R.string.string_progress_message));
				// dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				dialog.show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void showDialg(String message) {
		if (dialog == null) {
			dialog = new ProgressDialog(mContext);
			dialog.setCanceledOnTouchOutside(false);
		}
		if (!dialog.isShowing()) {
			dialog.setMessage(message);
			// dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.show();
		}
	}

	public void disMissDialog() {
		if (dialog != null) {
			dialog.dismiss();
		}
	}

	public void dealError(int errorCode, String errorMsg) {
		if (errorCode == 0) {
			showShortToast(errorMsg);

		} else if (errorCode == 1) {
			showShortToast("用户登录已过期，请重新登录");
			startActivity(LoginActivity.class);
			for (Activity activity : AppSet.activityStack) {
				activity.finish();
			}
		} else if (errorCode == 2) {
			showShortToast("app已下架");
			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);
			System.exit(0);
		} else if (errorCode == 3) {
			showShortToast("发现新版本，需要强制升级");
			String msg[] = errorMsg.split(",");
			downLoadMsg = msg[0];
			downLoadUrl = msg[1] + "&os=AndroidPOS&deviceType=" + Build.MODEL + "&longitude=" + NetParams.longitude
					+ "&latitude=" + NetParams.latitude;
			// listener.onError(requestId, 3, headResp.optString("retMsg1") +
			// "," + headResp.optString("retMsg2"));
			startUpdate();
		} else if (errorCode == 4) {
			showShortToast(errorMsg);
		}
	}

	public void startUpdate() {
		updateDialog.showDialog(downLoadMsg, new OnClickListener() {

			@Override
			public void onClick(View v) {
				String[] args2 = { "chmod", "604", InstallUtils.getApkFilePath(mContext) };
				InstallUtils.exec(args2);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse("file://" + InstallUtils.getApkFilePath(mContext)),
						"application/vnd.android.package-archive");
				startActivity(intent);

			}
		});

		Log.e("TAG", "startUpdate: "+downLoadUrl );
		DownloadRequest.getInstance(mContext).startDownload(downLoadUrl, 0, InstallUtils.getApkFilePath(mContext), true,
				appLoadListener);
	}

	private LoadListener appLoadListener = new LoadListener() {

		@Override
		public void onStart(int requestId) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			Log.e(Tag, "errorMsg=" + errorMsg);

		}

		@Override
		public void onSuccess(int requestId, String url, String result) {
			Log.e("result", result);
			updateDialog.setComplete();
			String[] args2 = { "chmod", "604", InstallUtils.getApkFilePath(mContext) };
			InstallUtils.exec(args2);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse("file://" + InstallUtils.getApkFilePath(mContext)),
					"application/vnd.android.package-archive");
			startActivity(intent);

		}

		@Override
		public void onLoading(long count, long current) {
			Log.e(Tag, "current/count=" + current + "/" + count);

			int progress = (int) (current * 100 / count);

			updateDialog.showProgress(progress, progress + "%");
		}
	};

}
